import re,sys,time
from flask import request, jsonify, session,g,current_app
from ..func.token_auth import auth as http_auth
from ..models import User
from . import auth
from .. import db
from response_code import RET
from ..func.redis_conn import r_db

@auth.route("")
@http_auth.login_required
def test():
    # current_app.logger.info('auth')
    return "auth"


# 邮箱注册
@auth.route("/register_email", methods=["POST"])
def register_by_email():
    # 接受的数据格式{"name":"",...}
    user_data = request.get_json()
    # print(user_data)
    name = user_data.get("name")
    email = user_data.get("email")
    password = user_data.get("password")
    password2 = user_data.get("password2")
    if not all([name, password, password2, email]):
        return jsonify({'code': 1001, "msg": "参数不完整"})
    elif not re.match("\w{6,18}", name):
        return jsonify({'code': 1003, "msg": "用户名输入不合法，请重新输入"})
    elif password != password2:
        return jsonify({'code': 1003, "msg": "两次密码不一致"})
    # user = User.query.filter_by(name=name).first()
    try:
        user = User.query.filter_by(name=name).first()
        # print(user.name,user.email)
    except Exception as e:
        print(e)
        return jsonify({"code": 5001, 'msg': '数据库查询错误'})
    if user:
        return jsonify({"code": 1004, 'msg': '用户已存在'})
    try:
        user = User.query.filter_by(email=email).first()
    except:
         return jsonify({"code": 5001, 'msg': '数据库查询错误'})
    if user:
        return jsonify({"code": 1004, 'msg': "邮箱已注册"})
    try:
        user = User(name=name, password=password, email=email)
        db.session.add(user)
        db.session.commit()
    except:
        db.session.rollback()
        return jsonify({'code': 5001, 'msg': "数据库错误"})
    return jsonify({'code': 200, 'msg': "注册成功"})


# 手机注册
@auth.route("/register_phone", methods=["POST"])
def register_by_phone():
    if request.method == 'POST':
        # 接受的数据格式{"name":"",...}
        user_data = request.get_json()
        print(user_data)
        name = user_data.get("name")
        phone = user_data.get("phone")
        password = user_data.get("password")
        password2 = user_data.get("password2")
        info = ""
        if not all([name, password, password2, phone]):
            return jsonify({'code':RET.PARAMERR, "error": "参数不完整"})
        elif not re.match("\w{6,18}", name):
            return jsonify({'code': RET.PARAMERR, "error": "用户名输入不合法，请重新输入"})
        elif password != password2:
            return jsonify({'code': RET.PARAMERR, "error": "两次密码不一致"})
        try:
            user = db.session.query(User).filter_by(name=name).first()
        except:
            return jsonify({"code": RET.DBERR, 'msg': '数据库查询错误'})
        if user:
            return jsonify({"code": RET.DATAEXIST, 'msg': '用户已存在'})
        try:
            user = User(
                name=name,
                password=password,
                phone=phone
            )
            db.session.add(user)
            db.session.commit()
        except:
            db.session.rollback()
            return jsonify({'code':RET.DBERR, 'msg': "数据库错误"})
        return jsonify({'code': RET.OK, 'msg': "注册成功"})



# 显示所有用户
@auth.route('/users')
def users():
    try:
        user = db.session.query(
            User.id, User.name, User.password, User.email, User.phone, User.addtime).all()
        print(user)
    except:
        return jsonify({'code': 2, 'msg': '数据库查询错误', })
    return jsonify({'code': 0, 'msg': 'ok', 'data': user})


#--------------------------用户信息----------------------------------------

@auth.route("/info",methods=["POST"])
@http_auth.login_required
def get_user_info():
    # print(request.headers)
    if not g.user_id:
        current_app.logger.error(sys._getframe().f_code.co_name)
        return jsonify(code=RET.REQERR,message="无权请求此接口",data="")
    user_id =g.user_id
    try:
        user=db.session.query(User.id,User.name).filter(User.id==user_id).first()
    except:
        return jsonify(code=RET.DBERR,message="数据库查询错误")
    return jsonify(
        {"code":0,
         "message":"加载成功",
         "data":
             {"roles":["admin"],
              "introduction":"I am a super administrator",
              "avatar":"https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif",
              "name":user.name}})

# 注销登录
@auth.route("/logout",methods=["POST"])
@http_auth.login_required
def logout():
    user_id = g.user_id
    uuid = g.uuid
    name = current_app.config["REDIS_PREFIX"] + str(user_id) + "_" + str(uuid)
    r_db.setex(name=name, value="", time=1)
    return jsonify(code=RET.OK,data="success",message="注销成功")

